import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  InputNumber,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { Course } from "../../../types/admin";
import { useUser } from "../../../contexts/UserContext";
import { adminAPI } from "../../../services/api";
import PermissionGuard from "../../../components/PermissionGuard";

const { Search } = Input;
const { confirm } = Modal;
const { TextArea } = Input;

const CourseManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [courses, setCourses] = useState<Course[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCourse, setEditingCourse] = useState<Course | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState("");

  // 获取课程列表
  const fetchCourses = async (params?: any) => {
    try {
      setLoading(true);
      console.log("📚 获取课程列表...", params);

      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 300)); // 模拟加载延迟
      
        const mockCourses: Course[] = [
          {
            id: "c1",
          name: "操作系统原理",
            code: "CS301",
          description: "学习操作系统的基本概念、原理和实现技术，包括进程管理、内存管理、文件系统等",
            teacher: {
              id: "t1",
            name: "张教授",
            },
            schedule: "周一 1-2节",
            location: "教学楼A-301",
            capacity: 60,
            enrolled: 45,
            status: "active",
          createTime: "2024-01-10",
        },
        {
          id: "c2",
          name: "数据结构与算法",
          code: "CS302",
          description: "学习基本数据结构（数组、链表、栈、队列、树、图）和经典算法设计方法",
          teacher: {
            id: "t2",
            name: "李副教授",
          },
          schedule: "周二 3-4节",
          location: "教学楼A-302",
          capacity: 55,
          enrolled: 52,
          status: "active",
          createTime: "2024-01-11",
        },
        {
          id: "c3",
          name: "计算机网络",
          code: "CS303",
          description: "学习计算机网络的基本原理、协议和网络编程技术",
          teacher: {
            id: "t1",
            name: "张教授",
          },
          schedule: "周三 1-2节",
          location: "教学楼A-303",
          capacity: 50,
          enrolled: 38,
          status: "active",
          createTime: "2024-01-12",
        },
        {
          id: "c4",
          name: "数据库原理",
          code: "CS304",
          description: "学习数据库系统的基本概念、关系数据库理论和SQL语言",
          teacher: {
            id: "t4",
            name: "赵副教授",
          },
          schedule: "周四 3-4节",
          location: "教学楼A-304",
          capacity: 45,
          enrolled: 42,
          status: "active",
          createTime: "2024-01-13",
        },
        {
          id: "c5",
          name: "软件工程",
          code: "SE301",
          description: "学习软件工程的基本原理、方法和工具，包括需求分析、设计、测试等",
          teacher: {
            id: "t3",
            name: "王讲师",
          },
          schedule: "周五 1-2节",
          location: "教学楼B-201",
          capacity: 40,
          enrolled: 35,
          status: "active",
          createTime: "2024-01-14",
        },
        {
          id: "c6",
          name: "机器学习",
          code: "AI301",
          description: "学习机器学习的基本算法、模型和应用，包括监督学习、无监督学习等",
          teacher: {
            id: "t5",
            name: "钱教授",
          },
          schedule: "周一 3-4节",
          location: "教学楼C-101",
          capacity: 35,
          enrolled: 32,
          status: "active",
          createTime: "2024-01-15",
        },
        {
          id: "c7",
          name: "网络安全基础",
          code: "NS301",
          description: "学习网络安全的基本概念、威胁模型和防护技术",
          teacher: {
            id: "t7",
            name: "周副教授",
          },
          schedule: "周二 1-2节",
          location: "教学楼C-102",
          capacity: 30,
          enrolled: 28,
          status: "active",
          createTime: "2024-01-16",
        },
        {
          id: "c8",
          name: "Web开发技术",
          code: "CS305",
          description: "学习现代Web开发技术，包括前端框架、后端开发和数据库集成",
          teacher: {
            id: "t3",
            name: "王讲师",
          },
          schedule: "周三 3-4节",
          location: "教学楼B-202",
          capacity: 40,
          enrolled: 25,
          status: "inactive",
          createTime: "2024-01-17",
          },
        ];

      // 如果有搜索参数，进行过滤
      let filteredCourses = mockCourses;
      if (params?.search) {
        const searchText = params.search.toLowerCase();
        filteredCourses = mockCourses.filter(
          course =>
            course.name.toLowerCase().includes(searchText) ||
            course.code.toLowerCase().includes(searchText) ||
            course.description.toLowerCase().includes(searchText) ||
            course.teacher.name.toLowerCase().includes(searchText)
        );
      }

      setCourses(filteredCourses);
      console.log("✅ 获取课程列表成功:", filteredCourses.length + "条记录");
    } catch (error) {
      console.error("❌ 获取课程列表失败:", error);
      message.error("获取课程列表失败，请检查网络连接");
      setCourses([]);
    } finally {
      setLoading(false);
    }
  };

  // 创建课程
  const createCourse = async (data: any) => {
    try {
      console.log("➕ 创建课程...", data);

      // 模拟创建成功
      await new Promise((resolve) => setTimeout(resolve, 200));

        message.success("创建课程成功");
        fetchCourses(); // 重新获取列表
        return true;
    } catch (error) {
      console.error("❌ 创建课程失败:", error);
      message.error("创建课程失败");
      return false;
    }
  };

  // 更新课程
  const updateCourse = async (id: string, data: any) => {
    try {
      console.log("📝 更新课程...", id, data);

      // 模拟更新成功
      await new Promise((resolve) => setTimeout(resolve, 200));

        message.success("更新课程信息成功");
        fetchCourses(); // 重新获取列表
        return true;
    } catch (error) {
      console.error("❌ 更新课程失败:", error);
      message.error("更新课程信息失败");
      return false;
    }
  };

  // 删除课程
  const deleteCourse = async (id: string) => {
    try {
      console.log("🗑️ 删除课程...", id);

      // 模拟删除成功
      await new Promise((resolve) => setTimeout(resolve, 200));

        message.success("删除课程成功");
        fetchCourses(); // 重新获取列表
        return true;
    } catch (error) {
      console.error("❌ 删除课程失败:", error);
      message.error("删除课程失败");
      return false;
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchCourses();
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
    // 调用API进行搜索
    fetchCourses({ search: value });
  };

  const showEditModal = (course: Course | null) => {
    setEditingCourse(course);
    setModalVisible(true);
    if (course) {
      form.setFieldsValue(course);
    } else {
      form.resetFields();
    }
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除这门课程吗？此操作不可恢复。",
      onOk: async () => {
        try {
          await deleteCourse(id);
        } catch (error) {
          message.error("删除失败");
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingCourse) {
        await updateCourse(editingCourse.id, values);
      } else {
        await createCourse(values);
      }
      setModalVisible(false);
    } catch (error) {
      message.error("提交失败");
    }
  };

  const columns = [
    {
      title: "课程名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "课程代码",
      dataIndex: "code",
      key: "code",
    },
    {
      title: "任课教师",
      dataIndex: ["teacher", "name"],
      key: "teacher",
    },
    {
      title: "上课时间",
      dataIndex: "schedule",
      key: "schedule",
    },
    {
      title: "上课地点",
      dataIndex: "location",
      key: "location",
    },
    {
      title: "选课情况",
      key: "enrollment",
      render: (_: unknown, record: Course) => (
        <span>
          {record.enrolled}/{record.capacity}
        </span>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : "red"}>
          {status === "active" ? "进行中" : "已结束"}
        </Tag>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Course) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="course.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => showEditModal(null)}
              >
                添加课程
              </Button>
              <Search
                placeholder="搜索课程..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={courses}
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </Space>
        </Card>

        <Modal
          title={editingCourse ? "编辑课程" : "添加课程"}
          open={modalVisible}
          onOk={handleModalOk}
          onCancel={() => setModalVisible(false)}
          destroyOnClose
          width={600}
        >
          <Form form={form} layout="vertical">
            <Form.Item
              name="name"
              label="课程名称"
              rules={[{ required: true, message: "请输入课程名称" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="code"
              label="课程代码"
              rules={[{ required: true, message: "请输入课程代码" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name={["teacher", "id"]}
              label="任课教师"
              rules={[{ required: true, message: "请选择任课教师" }]}
            >
              <Select>
                <Select.Option value="t1">张教授</Select.Option>
                <Select.Option value="t2">李副教授</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="description"
              label="课程描述"
              rules={[{ required: true, message: "请输入课程描述" }]}
            >
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item
              name="schedule"
              label="上课时间"
              rules={[{ required: true, message: "请输入上课时间" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="location"
              label="上课地点"
              rules={[{ required: true, message: "请输入上课地点" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="capacity"
              label="课程容量"
              rules={[{ required: true, message: "请输入课程容量" }]}
            >
              <InputNumber min={1} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
              name="status"
              label="课程状态"
              rules={[{ required: true, message: "请选择课程状态" }]}
            >
              <Select>
                <Select.Option value="active">进行中</Select.Option>
                <Select.Option value="inactive">已结束</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PermissionGuard>
  );
};

export default CourseManagement;
